var send = require('./sendData')
var mongodb = require('../plugs/mongose/mongoQuery')
var Config = require('../config/index').Config
var userTimeRun = function (token, bk, res) {
  mongodb.findOne("user", {
    token: token
  }, function (err, data) {
    if (data) {
      var mTime = data.date;
      // mTime = new Date(mTime).getTime();
      var nTime = new Date().getTime();
      var bTime = nTime - mTime;
      // console.log(nTime)
      // console.log(mTime)
      bTime = bTime / 1000; //转换为秒
      // console.log(bTime)
      // console.log(Config.outTime)
      if (bTime > Config.outTime) {
        send(res, false, 1);
      } else {
        //更新服务端的时间
        mongodb.update("user", {
          token: token
        }, {
          date: nTime
        }, function (err, data) {
        });
        bk(data);
      }
    } else {
      send(res, false, 1);
    }
  });
};
// 校验token
var authToken = function (req,res,next) {
  mongodb.findOne("user", {
    token: req.token
  }, function (err, data) {
    if (data) {
      var mTime = data.date;
      var nTime = new Date().getTime();
      var bTime = nTime - mTime;
      bTime = bTime / 1000; //转换为秒
      if (bTime > Config.outTime) {
        send(res, false, 1);
      } else {
        //更新服务端的时间
        mongodb.update("user", {
          token: token
        }, {
          date: nTime
        }, function (err, data) {
        });
        req.userId = data._id
		next()
      }
    } else {
      send(res, false, 1);
    }
  });
};
module.exports = userTimeRun
